package com.itlong.cloud.controller.settings;

import com.itlong.cloud.POJO.DTO.property.PropertyPadListDTO;
import com.itlong.cloud.POJO.PO.ProductTypePO;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.property.PropertyPadGetOneVO;
import com.itlong.cloud.POJO.VO.property.PropertyPadListVO;
import com.itlong.cloud.annotation.AuthAccessRequired;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.enumerate.PropertyEquipTypeEnum;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.PropertyErrorCodeEnum;
import com.itlong.cloud.equip.property.IPropertyEquipServiceClient;
import com.itlong.cloud.equip.property.IPropertyPadServiceClient;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.page.Page;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <desc>
 *
 * </desc>
 */
@RestController
@RequestMapping("/device/pad")
public class PropertyPadController {
    private static Logger LOG = LoggerFactory.getLogger(PropertyEquipController.class);

    @Autowired
    IPropertyPadServiceClient iPropertyPadServiceClient;

    @Autowired
    IPropertyEquipServiceClient iPropertyEquipServiceClient;

    /**
     * <desc>
     *  平板分页列表
     * </desc>
     *
     * @param pageDTO
     * @return
     * @author Jiaqi.X
     * @createDate 2017/09/28
     */
    @RequestMapping(path = "list", method = RequestMethod.POST)
    @ResponseBody
    @AuthAccessRequired
    public Object list(PropertyPadListDTO pageDTO) {
        MessageVO messageVO;
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            pageDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyPadListDTO.class, request);
            Page<PropertyPadListVO> page = iPropertyPadServiceClient.getList(pageDTO);
            messageVO = new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), page);
        } catch (Exception e) {
            throw new DataAccessException("【物业_设备管理_平板list】获取分页列表失败", e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      删除
     * </desc>
     *
     * @param deviceUnique
     * @return
     * @author Jiaqi.X
     * @createDate 2017/09/28
     */
    @AuthAccessRequired
    @RequestMapping(path = "delete", method = RequestMethod.POST)
    @ResponseBody
    @LoggerInfo(operateDesc = LogDescConstant.PAD_DELETE_INFO_LOG_DESF)
    public Object delete(String deviceUnique) {
        MessageVO messageVO;
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            deviceUnique = request.getAttribute("deviceUnique") == null ? null : request.getAttribute("deviceUnique").toString();
            if(iPropertyPadServiceClient.delete(deviceUnique) > 0){
                messageVO = new MessageVO(deviceUnique, BaseErrorCodeEnum.SUCCESS.getErrorCode());
            }else{
                messageVO = new MessageVO(BaseErrorCodeEnum.ERROR.getErrorCode());
            }
        } catch (Exception e) {
            throw new DataAccessException("【物业_设备管理_平板delete】删除平板失败", e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      获取单个对象
     * </desc>
     *
     * @param deviceUnique
     * @return
     * @author Jiaqi.X
     * @createDate 2017/09/28
     */
    @RequestMapping(path = "getOne", method = RequestMethod.POST)
    @ResponseBody
    @AuthAccessRequired
    public Object getOne(String deviceUnique) {
        MessageVO messageVO;
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            deviceUnique = request.getAttribute("deviceUnique") == null ? null : request.getAttribute("deviceUnique").toString();
            messageVO = new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),iPropertyPadServiceClient.getOne(deviceUnique));
        } catch (Exception e) {
            throw new DataAccessException("【物业_设备管理_平板delete】获取单个对象失败", e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      更新平板数据
     * </desc>
     *
     * @param vo
     * @return
     * @author Jiaqi.X
     * @createDate 2017/09/28
     */
    @AuthAccessRequired
    @RequestMapping(path = "update", method = RequestMethod.POST)
    @ResponseBody
    @LoggerInfo(operateDesc = LogDescConstant.PAD_UPDATE_INFO_LOG_DESF)
    public Object update(PropertyPadGetOneVO vo) {
        MessageVO messageVO;
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            vo = HttpProtocolUtil.parseRequestParamToDTO(PropertyPadGetOneVO.class, request);
            PropertyPadGetOneVO oldPadGetOneVO = iPropertyPadServiceClient.getOne(vo.getDeviceUnique());
            //如果本项目已添加有效的批次号后，则需校验设备总数与项目下批次号之和的数量
//            List<String> str= iPropertyEquipServiceClient.getBatchNumber(vo.getProjectId(),"0");
//            if(str != null && !str.isEmpty()){
//                Integer deviceCountByProject = iPropertyEquipServiceClient.getDeviceCountByType(PropertyEquipTypeEnum.PAD.getType(),vo.getProjectId(),"");
//                Integer limitCountByProject = iPropertyEquipServiceClient.getDeviceCountByBatchNumber(vo.getProjectId(),PropertyEquipTypeEnum.PAD.getType()+"","");
//                if(limitCountByProject<=deviceCountByProject){
//                    return new MessageVO(PropertyErrorCodeEnum.EQUIP_COUNT_PROJECT_IS_ZERO.getErrorCode());
//                }
//            }
            //如果批次号不为空时则需校验批次号相对应的设备数量
            if(StringUtils.isNotEmpty(vo.getBatchNumber()) && (StringUtils.isEmpty(oldPadGetOneVO.getBatchNumber()) ||
                    (StringUtils.isNotEmpty(oldPadGetOneVO.getBatchNumber()) && !vo.getBatchNumber().equals(oldPadGetOneVO.getBatchNumber())))){
                Integer deviceCount = iPropertyEquipServiceClient.getDeviceCountByType(PropertyEquipTypeEnum.PAD.getType(),vo.getProjectId(),vo.getBatchNumber());
                Integer limitCount = iPropertyEquipServiceClient.getDeviceCountByBatchNumber(vo.getProjectId(),PropertyEquipTypeEnum.PAD.getType()+"",vo.getBatchNumber());
                if(deviceCount == null){
                    deviceCount = 0;
                }
                if(limitCount<=deviceCount){
                    return new MessageVO(PropertyErrorCodeEnum.EQUIP_COUNT_PROJECT_IS_LESS.getErrorCode());
                }
            }
            messageVO = new MessageVO(iPropertyPadServiceClient.update(vo), BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【物业_设备管理_更新平板数据update】更新平板数据", e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      添加平板数据
     * </desc>
     *
     * @param vo
     * @return
     * @author Jiaqi.X
     * @createDate 2017/09/28
     */
    @AuthAccessRequired
    @RequestMapping(path = "add", method = RequestMethod.POST)
    @ResponseBody
    @LoggerInfo(operateDesc = LogDescConstant.PAD_ADD_INFO_LOG_DESF)
    public Object add(PropertyPadGetOneVO vo) {
        MessageVO messageVO;
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            vo = HttpProtocolUtil.parseRequestParamToDTO(PropertyPadGetOneVO.class, request);
            //如果本项目已添加有效的批次号后，则需校验设备总数与项目下批次号之和的数量
            List<String> str= iPropertyEquipServiceClient.getBatchNumber(vo.getProjectId(),"0");
            if(str != null && !str.isEmpty()){
                Integer deviceCountByProject = iPropertyEquipServiceClient.getDeviceCountByType(PropertyEquipTypeEnum.PAD.getType(),vo.getProjectId(),"");
                Integer limitCountByProject = iPropertyEquipServiceClient.getDeviceCountByBatchNumber(vo.getProjectId(),PropertyEquipTypeEnum.PAD.getType()+"","");
                deviceCountByProject = deviceCountByProject==null?0:deviceCountByProject;
                if(limitCountByProject==null || limitCountByProject<=deviceCountByProject){
                    return new MessageVO(PropertyErrorCodeEnum.EQUIP_COUNT_PROJECT_IS_ZERO.getErrorCode());
                }
            }
            //如果批次号不为空时则需校验批次号相对应的设备数量
            if(StringUtils.isNotEmpty(vo.getBatchNumber())){
                Integer deviceCount = iPropertyEquipServiceClient.getDeviceCountByType(PropertyEquipTypeEnum.PAD.getType(),vo.getProjectId(),vo.getBatchNumber());
                Integer limitCount = iPropertyEquipServiceClient.getDeviceCountByBatchNumber(vo.getProjectId(),PropertyEquipTypeEnum.PAD.getType()+"",vo.getBatchNumber());
                if(deviceCount == null){
                    deviceCount = 0;
                }
                if(limitCount<=deviceCount){
                    return new MessageVO(PropertyErrorCodeEnum.EQUIP_COUNT_PROJECT_IS_LESS.getErrorCode());
                }
            }
            ProductTypePO productTypePO = iPropertyEquipServiceClient.getTypeId(PropertyEquipTypeEnum.PAD.getType());
            if (productTypePO != null) {
                vo.setProductTypeId(productTypePO.getTypePid());
            }
            messageVO = new MessageVO(iPropertyPadServiceClient.add(vo), BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【物业_设备管理_添加平板数据add】添加平板数据", e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      验证机号是否存在
     * </desc>
     *
     * @param projectId
     * @param deviceId
     * @return
     * @author Jiaqi.X
     * @createDate 2017/09/28
     */
    @RequestMapping(path = "checkPadDeviceRepeat", method = RequestMethod.POST)
    @ResponseBody
    public Object checkPadDeviceRepeat(String projectId,String deviceId,Integer type) {
        MessageVO messageVO;
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            projectId = request.getAttribute("projectId") == null ? null : request.getAttribute("projectId").toString();
            deviceId = request.getAttribute("deviceId") == null ? null : request.getAttribute("deviceId").toString();
            type = request.getAttribute("type") == null ? null : (Integer) request.getAttribute("type");
            Integer count = iPropertyPadServiceClient.checkPadDeviceRepeat(projectId,deviceId,type);
            messageVO = new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),count);
        } catch (Exception e) {
            throw new DataAccessException("【物业_设备管理_验证机号是否存在checkPadDeviceRepeat】验证机号是否存在", e);
        }
        return messageVO;
    }
}
